// Initialize IndexedDB connection
let db;
const dbRequest = indexedDB.open("XiaohongshuSearchDB", 1);

dbRequest.onupgradeneeded = function(event) {
  db = event.target.result;
  if (!db.objectStoreNames.contains("searchResults")) {
    const store = db.createObjectStore("searchResults", { keyPath: "id", autoIncrement: true });
    store.createIndex("query", "query", { unique: false });
    store.createIndex("timestamp", "timestamp", { unique: false });
  }
};

dbRequest.onsuccess = function(event) {
  db = event.target.result;
  loadStats();
};

dbRequest.onerror = function(event) {
  console.error("Error opening database:", event.target.error);
  showError("无法打开数据库，请刷新后重试");
};

// DOM elements
const viewDataBtn = document.getElementById("view-data");
const exportJsonBtn = document.getElementById("export-json");
const exportCsvBtn = document.getElementById("export-csv");
const clearDataBtn = document.getElementById("clear-data");
const dataView = document.getElementById("data-view");
const dataList = document.getElementById("data-list");
const searchInput = document.getElementById("search-input");
const countEl = document.getElementById("count");
const queryEl = document.getElementById("query");

// Event listeners
viewDataBtn.addEventListener("click", openDataView);
exportJsonBtn.addEventListener("click", exportJSON);
exportCsvBtn.addEventListener("click", exportCSV);
clearDataBtn.addEventListener("click", clearData);
searchInput.addEventListener("input", debounce(filterData, 300));

// Load initial stats
function loadStats() {
  if (!db) return;
  
  const transaction = db.transaction(["searchResults"], "readonly");
  const store = transaction.objectStore("searchResults");
  const countRequest = store.count();
  
  countRequest.onsuccess = function() {
    countEl.textContent = countRequest.result;
  };
  
  // Get latest query
  const index = store.index("timestamp");
  const request = index.openCursor(null, "prev");
  
  request.onsuccess = function(event) {
    const cursor = event.target.result;
    if (cursor) {
      queryEl.textContent = cursor.value.query;
    }
  };
}

// Open data view in a new window/tab
function openDataView() {
  chrome.tabs.create({
    url: chrome.runtime.getURL("data-view.html")
  });
}

// Load data from IndexedDB
function loadData(searchQuery = "") {
  if (!db) return;
  
  dataList.innerHTML = "";
  
  const transaction = db.transaction(["searchResults"], "readonly");
  const store = transaction.objectStore("searchResults");
  const index = store.index("timestamp");
  const request = index.openCursor(null, "prev");
  
  request.onsuccess = function(event) {
    const cursor = event.target.result;
    if (cursor) {
      const data = cursor.value;
      
      // Filter by search query if provided
      if (!searchQuery || data.query.toLowerCase().includes(searchQuery.toLowerCase())) {
        const item = document.createElement("div");
        item.className = "data-item";
        item.innerHTML = `
          <div class="query">${data.query}</div>
          <div class="time">时间: ${new Date(data.timestamp).toLocaleString()}</div>
          <div>结果数: ${data.data.result?.length || data.data.data?.length || 0}</div>
        `;
        
        item.addEventListener("click", () => {
          showDataDetail(data);
        });
        
        dataList.appendChild(item);
      }
      
      cursor.continue();
    }
  };
}

// Filter data by search query
function filterData() {
  const query = searchInput.value.trim();
  loadData(query);
}

// Export all data as JSON
function exportJSON() {
  if (!db) return;
  
  const transaction = db.transaction(["searchResults"], "readonly");
  const store = transaction.objectStore("searchResults");
  const request = store.getAll();
  
  request.onsuccess = function() {
    const data = request.result;
    const json = JSON.stringify(data, null, 2);
    
    // Create and download file
    const blob = new Blob([json], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `xiaohongshu_search_data_${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    
    URL.revokeObjectURL(url);
  };
}

// Export data as CSV
function exportCSV() {
  if (!db) return;
  
  const transaction = db.transaction(["searchResults"], "readonly");
  const store = transaction.objectStore("searchResults");
  const request = store.getAll();
  
  request.onsuccess = function() {
    const data = request.result;
    let csv = "ID,查询关键词,时间戳,结果数量,URL\n";
    
    data.forEach(item => {
      const resultCount = item.data.result?.length || item.data.data?.length || 0;
      csv += `${item.id},"${item.query}","${item.title}","${item.user.nickname}","${item.image}","${item.timestamp}",${resultCount},"${item.url}"\n`;
    });
    
    // Create and download file
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `xiaohongshu_search_data_${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    
    URL.revokeObjectURL(url);
  };
}

// Clear all data
function clearData() {
  if (!db) return;
  
  if (confirm("确定要删除所有已保存的数据吗？此操作不可撤销。")) {
    const transaction = db.transaction(["searchResults"], "readwrite");
    const store = transaction.objectStore("searchResults");
    const request = store.clear();
    
    request.onsuccess = function() {
      alert("数据已清空");
      countEl.textContent = "0";
      queryEl.textContent = "-";
      dataList.innerHTML = "";
    };
  }
}

// Show data detail (not implemented yet)
function showDataDetail(data) {
  alert(`查询: ${data.query}\n时间: ${new Date(data.timestamp).toLocaleString()}\n结果数: ${data.data.result?.length || data.data.data?.length || 0}`);
  // This could be expanded to show a modal with full data details
}

// Show error
function showError(message) {
  const errorDiv = document.createElement("div");
  errorDiv.style.color = "red";
  errorDiv.style.padding = "10px";
  errorDiv.textContent = message;
  document.body.insertBefore(errorDiv, document.body.firstChild);
}

// Debounce function for search input
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, arguments), wait);
  };
} 